package com.example.lib5.SparseAlgorithm;

public class SparseArray2 {
    public static void main(String[] args) {
        int chessArr1[][]=new int[11][11];
        chessArr1[1][2]=1;
        chessArr1[2][3]=2;
        for (int[] ints : chessArr1) {
            System.out.println();
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
        }
        /**
         * 先获取有效值，这里是2个
         * 对整个数组进行遍历，比较是否为0，来判断值
         */
        int count=0;
        for (int[] ints : chessArr1) {
            for (int anInt : ints) {
                if (anInt!=0) {
                    count++;
                }
            }
        }
        System.out.println("\n有效值的个数："+count);
        //设置稀疏数组的行与列
        int sparseArr[][]=new int[count+1][3];
        //todo 赋值
        //第一行的值
        sparseArr[0][0]=chessArr1.length;
        sparseArr[0][1]=chessArr1[0].length;
        sparseArr[0][2]=count;
        //剩下行的值
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j]!=0) {
                    sparseArr[i][0]=i;
                    sparseArr[i][1]=j;
                    sparseArr[i][2]=chessArr1[i][j];
                }
            }
        }
        //打印稀疏数组
        System.out.println("打印稀疏数组");
        for (int[] ints : sparseArr) {
            System.out.println();
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
        }
        //todo 恢复回去
        //大致行与列
        int renew[][]=new int[sparseArr[0][0]][sparseArr[0][1]];
        //赋值
        for (int i = 1; i < sparseArr.length; i++) {
            int i0 = sparseArr[i][0];
            int i1 = sparseArr[i][1];
            int i2 = sparseArr[i][2];
            renew[i0][i1]=i2;
        }
        System.out.println("\n打印稀疏数组还原");
        for (int[] ints : renew) {
            System.out.println();
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
        }






    }
}
